﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace HP
{
    public class currency
    {

        /// <summary>
        /// 初始化通讯口 返 回：成功则返回串口标识符>0，失败返回负值，见错误代码表
        /// </summary>
        /// <param name="port">取值为0～19时，表示串口1～20；为100时，表示USB口通讯，此时波特率无效。</param>
        /// <param name="baud">为通讯波特率9600～115200</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll", EntryPoint = "dc_init", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public extern static int dc_init(int port, int baud);

        /// <summary>
        /// 关闭通讯口
        /// </summary>
        /// <param name="icdev">标识符</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern short dc_exit(int icdev);

        /// <summary>
        /// 设置TypeA或者TypeB类型非接触式CPU卡
        /// </summary>
        /// <param name="icdev">端口标识</param>
        /// <param name="_CardType">A/B 类型</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern short dc_config_card(int icdev, char _CardType);


        /// <summary>
        /// 复位
        /// </summary>
        /// <param name="icdev">端口标识</param>
        /// <param name="sec">1</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern short dc_reset(int icdev, uint sec);


        /// <summary>
        /// 寻卡，能返回在工作区域内某张卡的序列号
        /// </summary>
        /// <param name="icdev">端口标识</param>
        /// <param name="_Mode">0——表示IDLE模式，一次只对一张卡操作；1——表示ALL模式，一次可对多张卡操作；2——表示指定卡模式，只对序列号等于snr的卡操作（高级函数才有）</param>
        /// <param name="Snr">返回的卡序列号</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern short dc_card(int icdev, char _Mode, ref ulong Snr);


        /// <summary>
        /// 卡上电复位函数
        /// </summary>
        /// <param name="icdev">端口标识</param>
        /// <param name="rlen">返回信息的长度</param>
        /// <param name="rbuff">返回的信息</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern short dc_pro_resethex(int icdev, ref byte rlen, ref byte rbuff);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="icdev">端口标识符</param>
        /// <param name="len">发送的信息长度</param>
        /// <param name="sbuff">存放要发送的信息</param>
        /// <param name="rlen">返回信息的长度</param>
        /// <param name="rbuff">存放返回的信息</param>
        /// <param name="tt">延迟时间，单位为：10ms</param>
        /// <param name="FG">分割长度。建议此值小于64</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern short dc_pro_commandlink_hex(int icdev, byte len, ref byte sbuff, ref byte rlen, ref byte rbuff, byte tt, byte FG);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="icdev">端口标识符</param>
        /// <param name="len">发送的信息长度</param>
        /// <param name="sbuff">存放要发送的信息</param>
        /// <param name="rlen">返回信息的长度</param>
        /// <param name="rbuff">存放返回的信息</param>
        /// <param name="tt">延迟时间，单位为：10ms</param>
        /// <param name="FG">分割长度。建议此值小于64</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern short dc_pro_commandlink(int icdev, byte len, ref byte sbuff, ref byte rlen, ref byte rbuff, byte tt, byte FG);

        

        /// <summary>
        /// 3DES加密
        /// </summary>
        /// <param name="str1">16字节密钥</param>
        /// <param name="str2">放源数据</param>
        /// <param name="len">放源数据的字节数</param>
        /// <param name="str3">目的数据</param>
        /// <returns></returns>
        [DllImport("jlnmg.dll", EntryPoint = "des_en3", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public extern static void des_en3(byte[] str1, byte[] str2, int len, byte[] str3);

        //__int16 dc_setcpu(HANDLE ICDev,unsigned char SAMID)

        /// <summary>
        /// 设置PSIM卡座
        /// </summary>
        /// <param name="icdev">dc_init 函数返回的端口标识符</param>
        /// <param name="samid">设置要操作的卡座号,0x0c为附卡座，0x0d 0x0e 0x0f各为SAM1 SAM2 SAM3 </param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern int dc_setcpu(int icdev, byte samid);

        //__int16 dc_cpuapdu(HANDLE ICDev,unsigned char slen,unsigned char * sbuff,unsigned char *rlen,unsigned char * rbuff)
        /// <summary>
        /// PSIM发送命令
        /// </summary>
        /// <param name="ICDev">函数返回的端口标识符</param>
        /// <param name="slen">发送的信息长度</param>
        /// <param name="sbuff">存放要发送的信息</param>
        /// <param name="rlen">返回信息的长度</param>
        /// <param name="rbuff">存放返回的信息</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern int dc_cpuapdu(int ICDev, byte slen, ref byte sbuff, ref byte rlen, ref byte rbuff);

        //__int16 dc_setcpupara(HANDLE ICDev,unsigned char cputype,unsigned char cpupro,unsigned char cpuetu)

        /// <summary>
        /// 设置CPU参数
        /// </summary>
        /// <param name="ICDev">函数返回的端口标识符</param>
        /// <param name="cputype">卡座类型，12=主卡座 13=SAM1卡座 14=SAM2卡座 15=SAM3卡座（十进制）</param>
        /// <param name="cpupro">卡的协议类型 =0表示T=0协议 =1表示T=1协议</param>
        /// <param name="cpuetu">卡操作时候的延时数据（十进制）不同波特率的卡，此参数的值不同， 对于9600波特率的卡cpuetu设置成92 对于38400波特率的卡cpuetu设置成20</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern int dc_setcpupara(int ICDev, byte cputype, byte cpupro, byte cpuetu);

        //__int16 dc_cpureset(HANDLE ICDev,unsigned char *rlen, unsigned char *rbuff)

        /// <summary>
        /// PSIM复位操作
        /// </summary>
        /// <param name="ICDev">函数返回的端口标识符</param>
        /// <param name="rlen">返回复位信息的长度</param>
        /// <param name="rbuff">存放返回的复位信息</param>
        /// <returns></returns>
        [DllImport("dcrf32.dll")]
        public static extern int dc_cpureset(int ICDev, ref byte rlen, ref byte rbuff);





        /// <summary>
        /// 3DES加密
        /// </summary>
        /// <param name="Key">密钥</param>
        /// <param name="shu">加密数据</param>
        /// <returns></returns>
        public static string HP_des3(string Key, string shu)
        {
            byte[] shus = new byte[8];//加密后的shu
            byte[] Keys = HP.currency.strToToHexByte(Key);//密钥
            HP.currency.des_en3(Keys, HP.currency.strToToHexByte(shu), 8, shus);
            string shustr = HP.currency.byteToHexStr(shus);
            return shustr;
        }

        /// <summary>
        /// 3DES解密
        /// </summary>
        /// <param name="str1">16字节密钥</param>
        /// <param name="str2">放源数据</param>
        /// <param name="len">放源数据的字节数</param>
        /// <param name="str3">目的数据</param>
        /// <returns></returns>
        [DllImport("jlnmg.dll", EntryPoint = "des_de3", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public extern static void des_de3(byte[] str1, byte[] str2, int len, byte[] str3);


        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }


        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }


        #region[将字符转化成HEX串---------------------------------------------]
        /// <summary>
        /// 将字符转化成HEX串
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符中间用空格分开，true，false</param>
        /// <returns></returns>
        public static string CharToHex(string s, bool fengefu)
        {
            System.Text.Encoding myHex = System.Text.Encoding.UTF8;
            byte[] bytes = myHex.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                int mark = Int16.Parse(string.Format("{00:X}", bytes[i]));
                if (mark >= 10)
                {
                    str += string.Format("{0:X}", bytes[i]);

                    if (fengefu && (i != bytes.Length - 1))
                    {
                        str += string.Format("{0}", " ");
                    }
                }
                else
                {
                    str += string.Format("0{0:X}", bytes[i]);

                    if (fengefu && (i != bytes.Length - 1))
                    {
                        str += string.Format("{0}", " ");
                    }
                }
            }
            return str.ToLower();
        }

        /// <summary>
        /// 将HEX码还原成字符
        /// </summary>
        /// <param name="hex">hex码</param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string HexToChar(string hex)//,string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            string Str = "";
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                    if (bytes[i] > 100)
                    {
                        Str += bytes[i].ToString("X");
                    }
                }
                catch
                {
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.UTF8;
            //.GetEncoding("");//charset);
            Str = Str + chs.GetString(bytes);
            return Str;
        }



        #endregion

        /// <summary>
        /// byte[]变字符取后N个
        /// </summary>
        /// <param name="rbuff"></param>
        /// <returns></returns>
        public static string HP_bytetostrremove(byte[] rbuff, int N)
        {
            string str = "";

            string Mees = System.Text.Encoding.ASCII.GetString(rbuff).Replace("\0", "");

            if (Mees.Length >= 4)
            {
                str = Mees.Remove(0, Mees.Length - N);
            }

            return str;
        }




        /// <summary>
        ///  建文件结构（不用）
        /// </summary>
        /// <returns></returns>
        public static int hp_mf(int icdev)
        {

            int i = 1;
            string Key = "00000000000000000000000000000000";//MF当前K
            string Key1 = "00000000000000000000000000000000";//删除MF要写的K
            //i = hp_comm(icdev, "802A000008FFFFFFFFFFFFFFFF");
            //i = hp_comm(icdev, "80E00000173F00FFFFF0FA01FFFF");
            //认证MF
            i = hp_mfgo(icdev, Key);
            if (i != 0)
            {
                MessageBox.Show("MF认证不成功！");
            }

            ////选择MF
            string str = "00A40000023F00";

            ////////////////////////////////////////////////////////////////////////
            //删除MF
            //str = "80EE000008";
            str = "80EE000000";
            byte len3 = (byte)(str.Length / 2);
            byte rlen3 = 0;
            byte[] sbuff3 = System.Text.Encoding.ASCII.GetBytes(str);
            byte[] rbuff3 = new byte[40];
            i = dc_pro_commandlink_hex(icdev, len3, ref sbuff3[0], ref rlen3, ref rbuff3[0], 7, 56);

            string Mees3 = System.Text.Encoding.ASCII.GetString(rbuff3).Replace("\0", "");
            string Meess3 = HP_bytetostrremove(rbuff3, 4);
            if (i != 0 || Meess3 != "9000")
            {
                if (Meess3 == "6982")
                {
                    i = hp_upmf(icdev, Key, Key1);
                    if (i != 0)
                    {
                        MessageBox.Show("修改MFK不成功！");
                    }
                }
                else
                {
                    MessageBox.Show("删除MF不成功！");
                }
            }
            else
            {
                //////////////////////////////////////////////////////////////////////////////
                ////选择MF
                str = "00A40000023F00";
                //byte len4 = (byte)(str.Length / 2);
                //byte rlen4 = 0;
                //byte[] sbuff4 = System.Text.Encoding.ASCII.GetBytes(str);
                //byte[] rbuff4 = new byte[300];

                //i = dc_pro_commandlink_hex(icdev, len4, ref sbuff4[0], ref rlen4, ref rbuff4[0], 7, 56);
                //string Mees4 = System.Text.Encoding.ASCII.GetString(rbuff4).Replace("\0", "");
                //string Meess4 = HP_bytetostrremove(rbuff4, 4);
                i = hp_comm(icdev, "00A40000023F00");
                if (i != 0)
                {
                    MessageBox.Show("选择MF不成功！");
                }
                /////////////////////////////////////////////////////////////////////////////////
                //建立密钥文件 
                str = "80E002000B1E0000001EF0FA0020FF00";
                str = "80E002000B1E00000030F0FA00FF";
                //byte len5 = (byte)(str.Length / 2);
                //byte rlen5 = 0;
                //byte[] sbuff5 = System.Text.Encoding.ASCII.GetBytes(str);
                //byte[] rbuff5 = new byte[300];

                //i = dc_pro_commandlink_hex(icdev, len5, ref sbuff5[0], ref rlen5, ref rbuff5[0], 7, 56);

                //string Mees5 = System.Text.Encoding.ASCII.GetString(rbuff5).Replace("\0", "");
                //string Meess5 = HP_bytetostrremove(rbuff5, 4);
                i = hp_comm(icdev, "80E002000B1E00000030F0FA00FF");
                if (i != 0)
                {
                    MessageBox.Show("建立密钥文件不成功！");
                }
                /////////////////////////////////////////////////////////////////////////////////
                //建立主控密钥
                str = "80D4010015390000FF0F00" + Key1;

                byte len6 = (byte)(str.Length / 2);
                byte rlen6 = 0;
                byte[] sbuff6 = System.Text.Encoding.ASCII.GetBytes(str);
                byte[] rbuff6 = new byte[300];

                i = dc_pro_commandlink_hex(icdev, len6, ref sbuff6[0], ref rlen6, ref rbuff6[0], 7, 56);

                string Mees6 = System.Text.Encoding.ASCII.GetString(rbuff6).Replace("\0", "");
                string Meess6 = HP_bytetostrremove(rbuff6, 4);
                if (i != 0 || Meess6 != "9000")
                {
                    MessageBox.Show("建立主控密钥不成功！");
                }
            }
            //////////////////////////////////////////////////////////////////////////////////
            //建立EF2文件
            //80E0 8200 0A 01 0040 03 0003 05 F0FA 00
            //01:二进制文件 0040：空间   03：SFI 0003：FID
            //str = "80E002000B00EF020040F0FA0000FF00";
            //byte len7 = (byte)(str.Length / 2);
            //byte rlen7 = 0;
            //byte[] sbuff7 = System.Text.Encoding.ASCII.GetBytes(str);
            //byte[] rbuff7 = new byte[300];

            //i = dc_pro_commandlink_hex(icdev, len7, ref sbuff7[0], ref rlen7, ref rbuff7[0], 7, 56);

            //string Mees7 = System.Text.Encoding.ASCII.GetString(rbuff7).Replace("\0", "");
            //string Meess7 = HP_bytetostrremove(rbuff7, 4);
            //if (i != 0 || Meess7 != "9000")
            //{
            //    MessageBox.Show("建立EF2文件不成功！");
            //}
            //认证MF
            //i = hp_mfgo(icdev, Key);
            //if (i != 0)
            //{
            //    MessageBox.Show("MF认证不成功！");
            //}
            //选择MF
            //i = hp_comm(icdev, "00A40000023F00");
            //if (i != 0)
            //{
            //    return 1;
            //}
            //建立EF2文件
            //80E002000B00EF020040F0FA0020FF00
            //80E002000B00EF020040F0F00000FF00
            //80E002000B000005001E00000520FF00
            //80E001000D10010999FAFA95080012345678
            i = hp_comm(icdev, "80E002000B000005001E00000520FF00");
            if (i != 0)
            {
                MessageBox.Show("MF认证不成功！");
            }
            return i;
        }



        /// <summary>
        /// 修改MFK
        /// </summary>
        /// <param name="icdev"></param>
        /// <returns></returns>
        public static int hp_upmf(int icdev, string Key, string Key1)
        {

            int i = 9;
            //选择MF
            //string str = "00A40000023F00";

            i = hp_mfgo(icdev, Key);
            if (i != 0)
            {
                MessageBox.Show("MF认证不成功！");
            }
            ////////////////////////////////////////////////////////////////////////////////
            // 80D4010015390000FF0F00
            //str = "80D4020015390000FF0100"+Key1;
            string str = "80D4390010" + Key1;
            byte len3 = (byte)(str.Length / 2);
            byte rlen3 = 0;
            byte[] sbuff3 = System.Text.Encoding.ASCII.GetBytes(str);
            byte[] rbuff3 = new byte[300];

            i = dc_pro_commandlink_hex(icdev, len3, ref sbuff3[0], ref rlen3, ref rbuff3[0], 7, 56);
            string Mees3 = System.Text.Encoding.ASCII.GetString(rbuff3).Replace("\0", "");
            string Meess3 = HP_bytetostrremove(rbuff3, 4);
            if (i != 0 || Meess3 != "9000")
            {
                i = 9;

            }


            return i;
        }


        /// <summary>
        /// MF认证
        /// </summary>
        /// <param name="icdev"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static int hp_mfgo(int icdev, string Key)
        {
            //选择MF
            int i = 9;
            string str = "00A40000023F00";
            //byte len = (byte)(str.Length / 2);
            //byte rlen = 0;
            //byte[] sbuff = System.Text.Encoding.ASCII.GetBytes(str);
            //byte[] rbuff = new byte[300];

            //i = dc_pro_commandlink_hex(icdev, len, ref sbuff[0], ref rlen, ref rbuff[0], 7, 56);
            //string Mees = System.Text.Encoding.ASCII.GetString(rbuff).Replace("\0", "");
            //string Meess = HP_bytetostrremove(rbuff, 4);
            //if (i != 0 || Meess != "9000")
            //{
            //    MessageBox.Show("选择MF不成功！");
            //}
            i = hp_comm(icdev, "00A40000023F00");
            if (i != 0)
            {
                return 1;
            }
            //取随机数

            str = "0084000008";
            byte len1 = (byte)(str.Length / 2);
            byte rlen1 = 0;
            byte[] sbuff1 = System.Text.Encoding.ASCII.GetBytes(str);
            byte[] rbuff1 = new byte[40];

            i = dc_pro_commandlink_hex(icdev, len1, ref sbuff1[0], ref rlen1, ref rbuff1[0], 7, 56);

            string Mees1 = System.Text.Encoding.ASCII.GetString(rbuff1).Replace("\0", "");
            string Meess1 = HP_bytetostrremove(rbuff1, 4);
            if (i != 0 || Meess1 != "9000")
            {
                return 1;
            }
            string shu1 = System.Text.Encoding.ASCII.GetString(rbuff1).Substring(0, ((int)rlen1) * 2 - 4);//取随机数

            ///////////////////////////////////////////////////////////////////////////////
            //加密
            string shustr2 = HP_des3(Key, shu1);

            //MF认证
            str = "0082000008" + shustr2;//取的加密的字符串
            //byte len2 = (byte)(str.Length / 2);
            //byte rlen2 = 0;
            //byte[] sbuff2 = System.Text.Encoding.ASCII.GetBytes(str);
            //byte[] rbuff2 = new byte[40];
            //i = dc_pro_commandlink_hex(icdev, len2, ref sbuff2[0], ref rlen2, ref rbuff2[0], 7, 56);

            //string Mees2 = System.Text.Encoding.ASCII.GetString(rbuff2).Replace("\0", "");
            //string Meess2 = HP_bytetostrremove(rbuff2, 4);
            //if (i != 0 || Meess2 != "9000")
            //{
            //    return 1;

            //}
            i = hp_comm(icdev, str);
            if (i != 0)
            {
                return 1;
            }
            return i;
        }


        /// <summary>
        /// 长安通MF认证
        /// </summary>
        /// <param name="icdev"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static int hp_029(int icdev, string Key)
        {
            //选择MF
            int i = 9;
            string str = "00A40000023F00";
            //byte len = (byte)(str.Length / 2);
            //byte rlen = 0;
            //byte[] sbuff = System.Text.Encoding.ASCII.GetBytes(str);
            //byte[] rbuff = new byte[300];

            //i = dc_pro_commandlink_hex(icdev, len, ref sbuff[0], ref rlen, ref rbuff[0], 7, 56);
            //string Mees = System.Text.Encoding.ASCII.GetString(rbuff).Replace("\0", "");
            //string Meess = HP_bytetostrremove(rbuff, 4);
            //if (i != 0 || Meess != "9000")
            //{
            //    MessageBox.Show("选择MF不成功！");
            //}
            i = hp_comm(icdev, "00A40000023F00");
            if (i != 0)
            {
                return 1;
            }
            //取随机数

            str = "0084000008";
            byte len1 = (byte)(str.Length / 2);
            byte rlen1 = 0;
            byte[] sbuff1 = System.Text.Encoding.ASCII.GetBytes(str);
            byte[] rbuff1 = new byte[40];

            i = dc_pro_commandlink_hex(icdev, len1, ref sbuff1[0], ref rlen1, ref rbuff1[0], 7, 56);

            string Mees1 = System.Text.Encoding.ASCII.GetString(rbuff1).Replace("\0", "");
            string Meess1 = HP_bytetostrremove(rbuff1, 4);
            if (i != 0 || Meess1 != "9000")
            {
                return 1;
            }
            string shu1 = System.Text.Encoding.ASCII.GetString(rbuff1).Substring(0, ((int)rlen1) * 2 - 4);//取随机数

            ///////////////////////////////////////////////////////////////////////////////
            //加密
            string shustr2 = HP_des3(Key, shu1);

            //MF认证
            str = "0082000008" + shustr2;//取的加密的字符串
            //byte len2 = (byte)(str.Length / 2);
            //byte rlen2 = 0;
            //byte[] sbuff2 = System.Text.Encoding.ASCII.GetBytes(str);
            //byte[] rbuff2 = new byte[40];
            //i = dc_pro_commandlink_hex(icdev, len2, ref sbuff2[0], ref rlen2, ref rbuff2[0], 7, 56);

            //string Mees2 = System.Text.Encoding.ASCII.GetString(rbuff2).Replace("\0", "");
            //string Meess2 = HP_bytetostrremove(rbuff2, 4);
            //if (i != 0 || Meess2 != "9000")
            //{
            //    return 1;

            //}
            i = hp_comm(icdev, str);
            if (i != 0)
            {
                return 1;
            }
            return i;
        }


        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="icdev"></param>
        /// <param name="str">命令</param>
        /// <returns></returns>
        public static int hp_comm(int icdev, string str)
        {
            byte len = (byte)(str.Length / 2);
            byte rlen = 0;
            byte[] sbuff = System.Text.Encoding.ASCII.GetBytes(str);
            byte[] rbuff = new byte[300];

            int i = dc_pro_commandlink_hex(icdev, len, ref sbuff[0], ref rlen, ref rbuff[0], 7, 56);
            string Mees = System.Text.Encoding.ASCII.GetString(rbuff).Replace("\0", "");
            string Meess = HP_bytetostrremove(rbuff, 4);

            if (i != 0 || Meess != "9000")
            {
                i = 9;

            }

            return i;
        }

        /// <summary>
        /// 读文件命令
        /// </summary>
        /// <param name="icdev"></param>
        /// <param name="str">命令</param>
        /// <returns></returns>
        public static int hp_Read(int icdev, string str, out string tostr)
        {
            byte len = (byte)(str.Length / 2);
            byte rlen = 0;
            byte[] sbuff = System.Text.Encoding.ASCII.GetBytes(str);
            byte[] rbuff = new byte[300];

            int i = dc_pro_commandlink_hex(icdev, len, ref sbuff[0], ref rlen, ref rbuff[0], 7, 56);
            string Mees = System.Text.Encoding.ASCII.GetString(rbuff).Replace("\0", "");
            tostr = Mees;
            string Meess = HP_bytetostrremove(rbuff, 4);

            if (i != 0 || Meess != "9000")
            {
                i = 9;

            }

            return i;
        }


        private static int icdev1;
        /// <summary>
        /// 打开设备
        /// </summary>
        /// <returns></returns>
        public static int HP_GO()
        {
            int i = 999;//成功标识
            /////////////////////////////////////////
            icdev1 = HP.currency.dc_init(100, 115200);//取设备标识
            //this.button1.Text = icdev.ToString();
            if (icdev1 <= 0)
            {
                MessageBox.Show("打开设备不成功！");
                return 1;
            }

            ////////////////////////////////////////

            i = HP.currency.dc_config_card(icdev1, 'A');
            if (i != 0)
            {
                MessageBox.Show("设置卡类型不成功！");
                return 1;
            }

            ///////////////////////////////////////

            i = HP.currency.dc_reset(icdev1, 1);
            if (i != 0)
            {
                MessageBox.Show("复位不成功！");
                return 1;
            }

            //////////////////////////////////////

            ulong icCardNo = 0;//返回的卡序列号
            i = HP.currency.dc_card(icdev1, '0', ref icCardNo);
            if (i != 0)
            {
                MessageBox.Show("寻卡不成功！");
                return 1;

            }

            /////////////////////////////////////

            byte crlen = 1;//返回的信息数
            byte[] recbuff = new byte[32];//返回的信息

            i = HP.currency.dc_pro_resethex(icdev1, ref crlen, ref recbuff[0]);
            if (i != 0)
            {
                MessageBox.Show("卡复位不成功！");
                return 1;

            }

            return i;
        }


        /// <summary>
        /// 王曦测试
        /// </summary>
        public static void wx_cs()
        {
            int goid = HP.currency.dc_init(100, 115200);//取设备标识;
            if (goid <= 0) //返加>0成功
            {
                //MessageBox.Show("设备没有打开！");
                return;
            }




            /////////////////////////////////////////
            //操作消费卡开始
            int i = 999;//成功标识
            //////////////////////////////////////////

            i = HP.currency.dc_config_card(goid, 'A');
            if (i != 0)
            {
                //MessageBox.Show("设置卡类型不成功！");
                dc_exit(goid);
                return;
            }

            ///////////////////////////////////////

            i = HP.currency.dc_reset(goid, 1);
            if (i != 0)
            {
                //MessageBox.Show("射频复位不成功！");
                dc_exit(goid);
                return;
            }

            //////////////////////////////////////

            ulong icCardNo = 0;//返回的卡序列号
            i = HP.currency.dc_card(goid, '0', ref icCardNo);
            if (i != 0)
            {
                //MessageBox.Show("寻卡不成功！");
                dc_exit(goid);
                return;

            }

            /////////////////////////////////////

            byte crlen = 1;//返回的信息数
            byte[] recbuff = new byte[32];//返回的信息

            i = HP.currency.dc_pro_resethex(goid, ref crlen, ref recbuff[0]);
            if (i != 0)
            {
                //MessageBox.Show("卡复位不成功！");
                dc_exit(goid);
                return;

            }

            ///////////////////////////////////////

            //选择MF


            i = hp_comm(goid, "00A4040009A0000000038698070100");
            if (i != 0)
            {
                dc_exit(goid);
                return;
            }

            
           
           
            string 返回 = "";

            string 自来水基本信息 = cmd(goid, "00B09C0000", ref 返回);
            //0101021000000010011111201802050101016501850200000380000390000410000510000000000000000000000000009000
            string 读取账单 = cmd(goid, "00B201E800", ref 返回);
            //0140101015030001010001201802050000000000010000201802050001000020280101000000000000000000000000000000000000000000000000000000000000009000
            string 读零一记录 = cmd(goid, "00B201EC00", ref 返回);
            //0140101015030001010001201802050000000000010000201802050001000020280101000000000000000000000000000000000000000000000000000000000000009000
            string 读零二记录 = cmd(goid, "00B202EC00", ref 返回);
            //0240101015030001020000000000000000000000010000201802050001000000000000000000000000000000000000000000000000000000000000000000000000009000
        
        }






        /// <summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static string GetChsFromHex(string hex)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
                            //throw new ArgumentException("hex is not a valid number!", "hex");
            }
            // 需要将 hex 转换成 byte 数组。
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                        System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message.
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }

            // 获得 GB2312，Chinese Simplified。
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");


            return chs.GetString(bytes);
        }




        /// <summary>
        /// 长安通
        /// </summary>
        /// <returns></returns>
        public static void HP_GetUserName(ref List<string> carddata)
        {

            //            3930454435444344202020202020202020202020
            //36313031303331393738313230313336333   32020202020202020202020202020


            //180
            //3446353537334232202020202020202020202020
            //363132353232313938373034323232363258   2020202020202020202020202020






            //  string aaaa = GetChsFromHex("4646393745394646394534462020202020202020");

            //  string name1 = ASCtoGB("3930454435444344202020202020202020202020");
            // string sfz1= 身份证件("3631303130333139373831323031333633332020202020202020202020202020");

            //  string sfz1 = 身份证件("3631323532323139383730343232323632582020202020202020202020202020");



            //return;





            //carddata = new List<string> ();


            //DataSet ds = ClassHelp.XmlObject.GetXml(Application.StartupPath + @"\C.xml");



            int goid = HP.currency.dc_init(100, 115200);//取设备标识;
            if (goid <= 0) //返加>0成功
            {
                //MessageBox.Show("设备没有打开！");
                return;
            }




            /////////////////////////////////////////
            //操作消费卡开始
            int i = 999;//成功标识
            //////////////////////////////////////////

            i = HP.currency.dc_config_card(goid, 'A');
            if (i != 0)
            {
                //MessageBox.Show("设置卡类型不成功！");
                dc_exit(goid);
                return;
            }

            ///////////////////////////////////////

            i = HP.currency.dc_reset(goid, 1);
            if (i != 0)
            {
                //MessageBox.Show("射频复位不成功！");
                dc_exit(goid);
                return;
            }

            //////////////////////////////////////

            ulong icCardNo = 0;//返回的卡序列号
            i = HP.currency.dc_card(goid, '0', ref icCardNo);
            if (i != 0)
            {
                //MessageBox.Show("寻卡不成功！");
                dc_exit(goid);
                return;

            }

            /////////////////////////////////////

            byte crlen = 1;//返回的信息数
            byte[] recbuff = new byte[32];//返回的信息

            i = HP.currency.dc_pro_resethex(goid, ref crlen, ref recbuff[0]);
            if (i != 0)
            {
                //MessageBox.Show("卡复位不成功！");
                dc_exit(goid);
                return;

            }

            ///////////////////////////////////////

            //选择MF


            i = hp_comm(goid, "00A40000023F00");
            if (i != 0)
            {
                dc_exit(goid);
                return;
            }

            string 返回1 = "";
            string 执行结果 = cmd(goid, "00B0850000", ref 返回1);

            string cardids = 执行结果.Substring(16, 16);////str.Append(CardId);//	N16	卡内号
            string cardhao = (Convert.ToInt32(cardids.Substring(8, 8), 16)).ToString().PadLeft(8, '0'); ;
            string cdid = cardids.Substring(0, 8) + cardhao;

            i = hp_comm(goid, "00A4040009A00000000386980701");
            if (i != 0)
            {
                dc_exit(goid);
                return;
            }

            //i = hp_comm(goid, "00A4040009A00000000386980701");
            //if (i != 0)
            //{
            //    dc_exit(goid);
            //    return;
            //}


            //int  yyi = hp_comm(goid, "00B0950000");//卡类型
            string 返回11 = "";
            string 执行结果1111 = cmd(goid, "00B0960000", ref 返回11);
            string tag = 执行结果1111.Substring(3 * 2 - 2, 20 * 2);
            string tagsfz = 执行结果1111.Substring(23 * 2 - 2, 32 * 2);
            if (tag == "0000000000000000000000000000000000000000")
            {
                //MessageBox.Show
                CCWin.MessageBoxEx.Show(" 卡中无正确姓名！");
                dc_exit(goid);
                return;
            }
            string name = ASCtoGB(tag);
            string sfz = 身份证件(tagsfz);

            carddata.Add(name);
            carddata.Add(sfz);
            carddata.Add(cardhao);//卡面号
                                  //  ASCtoGB
                                  // 身份证件





            //foreach (DataRow dr in ds.Tables ["命令"].Rows)
            //{
            //    string 命令_id = dr["命令_Id"].ToString().Trim();
            //    string 名称 = dr["名称"].ToString().Trim();
            //    string 类型 = dr["类型"].ToString().Trim();
            //    string 执行 = dr["执行"].ToString().Trim();
            //    string 文本显示 = dr["文本"].ToString().Trim();
            //    string 返回 = "";
            //    string 执行结果 ="";

            //    if (类型 == "选择应用")
            //    {
            //        i = hp_comm(goid, 执行);
            //        if (i != 0)
            //        {
            //            dc_exit(goid);
            //            return;
            //        }
            //        continue;
            //    }
            //    else if (类型 == "记录文件")
            //    {

            //        DataTable jldt = 记录文件(goid, ds, dr);
            //        string clnames = "";
            //        foreach (var aacl in jldt.Columns)
            //        {
            //            clnames += aacl + "------";
            //        }
            //        carddata.Add(clnames);
            //        foreach (DataRow  jldtdr in jldt.Rows )
            //        {
            //             clnames = "";
            //            for (int iii = 0; iii < jldt.Columns.Count; iii++)
            //            {

            //                //carddata.Add(aadr[0] + "---" + aadr[1] + "---" + aadr[2] + "---" + aadr[3]);

            //                clnames += jldtdr[iii]+"-----";


            //                //carddata.Add(String .Join ("---",aadr.ItemArray));
            //            }
            //            carddata.Add(clnames);

            //        }

            //        continue;
            //    }

            //    执行结果 = cmd(goid, 执行, ref 返回);

            //    carddata.Add("");
            //    carddata.Add(文本显示);

            //    if (返回 == "9000")
            //    {
            //        DataRow[] drs = ds.Tables["解析"].Select("命令_Id=" + 命令_id);
            //        foreach (DataRow ddrr in drs)
            //        {
            //            string 文本 = ddrr["文本"].ToString().Trim();
            //            string 开始位 = ddrr["开始位"].ToString().Trim();
            //            string 长度 = ddrr["长度"].ToString().Trim();
            //            string 转换方法 = ddrr["转换方法"].ToString().Trim();
            //            string 截取值="";

            //            if (开始位 == "")
            //            {
            //                截取值 = 执行结果.Substring(0, 执行结果.Length - 4);
            //            }
            //            else
            //            {
            //                截取值 = 执行结果.Substring(int.Parse(开始位) * 2 - 2, int.Parse(长度) * 2);
            //            }

            //            switch (转换方法.ToUpper())
            //            {
            //                case "ASC":
            //                    截取值 = ASCtoGB(截取值);
            //                    break;
            //                case "16TO10":
            //                    截取值 = (Convert.ToInt32(截取值, 16)).ToString();
            //                    break;
            //                case "身份证件":
            //                    截取值 = 身份证件(截取值).ToString();
            //                    break;
            //            }

            //            string 输出值 = "";
            //            if (ds.Tables["解析"].Columns.Contains("解析_Id") == true)
            //            {
            //                string 解析_Id = ddrr["解析_Id"].ToString().Trim();

            //                DataRow[] 判断dr = ds.Tables["判断"].Select("解析_Id=" + 解析_Id + " and 条件='" + 截取值 + "'");

            //                if (判断dr.Length > 0)
            //                {
            //                    输出值 = 判断dr[0]["判断_Text"].ToString().Trim();
            //                }
            //                else
            //                {
            //                    输出值 =  截取值;
            //                }
            //            }
            //            else
            //            {
            //                输出值 = 截取值;
            //            }

            //            carddata.Add(String.Format(文本, 输出值));

            //        }
            //    }




            //}



            //00B0850000
            //string strm1 = "00B0850000"; //000046463937453946463945344620202020202020203631303130333139383630393239323431362020202020202020202020202020009000
            //byte lenm1 = (byte)(strm1.Length / 2);
            //byte rlenm1 = 0;
            //byte[] sbuffm1 = System.Text.Encoding.ASCII.GetBytes(strm1);
            //byte[] rbuffm1 = new byte[300];

            //i = dc_pro_commandlink_hex(goid, lenm1, ref sbuffm1[0], ref rlenm1, ref rbuffm1[0], 7, 56);
            //string Meesm1 = System.Text.Encoding.ASCII.GetString(rbuffm1).Replace("\0", "");
            //string Meessm1 = HP_bytetostrremove(rbuffm1, 4);
            //if (i != 0 || Meessm1 != "9000")
            //{
            //    //MessageBox.Show("16文件读取不成功！");
            //    dc_exit(goid);
            //    return;
            //}

            // carddata= Meesm1.Substring(4, 40);

            // carddata = ASCtoGB(carddata);

            ////////////////////////////////////////////////
            ////string strm = "805C000204";
            ////byte lenm = (byte)(strm.Length / 2);
            ////byte rlenm = 0;
            ////byte[] sbuffm = System.Text.Encoding.ASCII.GetBytes(strm);
            ////byte[] rbuffm = new byte[300];

            ////i = dc_pro_commandlink_hex(goid, lenm, ref sbuffm[0], ref rlenm, ref rbuffm[0], 7, 56);
            ////string Meesm = System.Text.Encoding.ASCII.GetString(rbuffm).Replace("\0", "");
            ////string Meessm = HP_bytetostrremove(rbuffm, 4);
            ////ymoney = Meesm.Remove(8);
            ////if (i != 0 || Meessm != "9000")
            ////{
            ////    MessageBox.Show("读取余额不成功！");
            ////}
            //////////////////////////////////////////////////
            ////i = hp_comm(goid, "00A4040009A00000000386980701");////选择应用

            ////if (i != 0)
            ////{
            ////    return;
            ////}

            ////00B0950000
            ////00A40000020016

            //string strm1 = "00B0960000"; //000046463937453946463945344620202020202020203631303130333139383630393239323431362020202020202020202020202020009000
            //byte lenm1 = (byte)(strm1.Length / 2);
            //byte rlenm1 = 0;
            //byte[] sbuffm1 = System.Text.Encoding.ASCII.GetBytes(strm1);
            //byte[] rbuffm1 = new byte[300];

            //i = dc_pro_commandlink_hex(goid, lenm1, ref sbuffm1[0], ref rlenm1, ref rbuffm1[0], 7, 56);
            //string Meesm1 = System.Text.Encoding.ASCII.GetString(rbuffm1).Replace("\0", "");
            //string Meessm1 = HP_bytetostrremove(rbuffm1, 4);
            //if (i != 0 || Meessm1 != "9000")
            //{
            //    //MessageBox.Show("16文件读取不成功！");
            //    dc_exit(goid);
            //    return;
            //}

            // carddata= Meesm1.Substring(4, 40);

            // carddata = ASCtoGB(carddata);
            ////DataRow[] rows = aaa(goid).Select("1=1");
            ////string[] arr = rows.s.Select(x => x[0].ToString()).ToArray();

            dc_exit(goid);
            ////MessageBox.Show("操作成功！");

        }





        /// <summary>
        /// 长安通
        /// </summary>
        /// <returns></returns>
        public static void HP_GetUserName_111111(ref List<string> carddata)
        {

//            3930454435444344202020202020202020202020
//36313031303331393738313230313336333   32020202020202020202020202020


//180
//3446353537334232202020202020202020202020
//363132353232313938373034323232363258   2020202020202020202020202020






          //  string aaaa = GetChsFromHex("4646393745394646394534462020202020202020");

          //  string name1 = ASCtoGB("3930454435444344202020202020202020202020");
           // string sfz1= 身份证件("3631303130333139373831323031333633332020202020202020202020202020");

          //  string sfz1 = 身份证件("3631323532323139383730343232323632582020202020202020202020202020");



            //return;





            //carddata = new List<string> ();


            //DataSet   ds= ClassHelp.XmlObject.GetXml(Application.StartupPath + @"\C.xml");



            int goid = HP.currency.dc_init(100, 115200);//取设备标识;
            if (goid <= 0) //返加>0成功
            {
                //MessageBox.Show("设备没有打开！");
                return;
            }
            



            /////////////////////////////////////////
            //操作消费卡开始
            int i = 999;//成功标识
            //////////////////////////////////////////

            i = HP.currency.dc_config_card(goid, 'A');
            if (i != 0)
            {
                //MessageBox.Show("设置卡类型不成功！");
                dc_exit(goid);
                return;
            }

            ///////////////////////////////////////

            i = HP.currency.dc_reset(goid, 1);
            if (i != 0)
            {
                //MessageBox.Show("射频复位不成功！");
                dc_exit(goid);
                return;
            }

            //////////////////////////////////////

            ulong icCardNo = 0;//返回的卡序列号
            i = HP.currency.dc_card(goid, '0', ref icCardNo);
            if (i != 0)
            {
                //MessageBox.Show("寻卡不成功！");
                dc_exit(goid);
                return;

            }

            /////////////////////////////////////

            byte crlen = 1;//返回的信息数
            byte[] recbuff = new byte[32];//返回的信息

            i = HP.currency.dc_pro_resethex(goid, ref crlen, ref recbuff[0]);
            if (i != 0)
            {
                //MessageBox.Show("卡复位不成功！");
                dc_exit(goid);
                return;

            }

            ///////////////////////////////////////

            //选择MF


            i = hp_comm(goid, "00A40000023F00");
            if (i != 0)
            {
                dc_exit(goid);
                return;
            }

            i = hp_comm(goid, "00A4040009A00000000386980701");
            if (i != 0)
            {
                dc_exit(goid);
                return;
            }

            //i = hp_comm(goid, "00A4040009A00000000386980701");
            //if (i != 0)
            //{
            //    dc_exit(goid);
            //    return;
            //}

            int  yyi = hp_comm(goid, "00B0950000");//卡类型
            string 返回11 = "";
            string  执行结果1111 = cmd(goid, "00B0960000", ref 返回11);
            string tag= 执行结果1111.Substring(3 * 2 - 2, 20 * 2);
            string tagsfz = 执行结果1111.Substring(23 * 2 - 2, 32 * 2);
            string name = ASCtoGB(tag);
            string sfz = 身份证件(tagsfz);

            carddata.Add(name);
            carddata.Add(sfz);
            //  ASCtoGB
            // 身份证件





            //foreach (DataRow dr in ds.Tables ["命令"].Rows)
            //{
            //    string 命令_id = dr["命令_Id"].ToString().Trim();
            //    string 名称 = dr["名称"].ToString().Trim();
            //    string 类型 = dr["类型"].ToString().Trim();
            //    string 执行 = dr["执行"].ToString().Trim();
            //    string 文本显示 = dr["文本"].ToString().Trim();
            //    string 返回 = "";
            //    string 执行结果 ="";

            //    if (类型 == "选择应用")
            //    {
            //        i = hp_comm(goid, 执行);
            //        if (i != 0)
            //        {
            //            dc_exit(goid);
            //            return;
            //        }
            //        continue;
            //    }
            //    else if (类型 == "记录文件")
            //    {

            //        DataTable jldt = 记录文件(goid, ds, dr);
            //        string clnames = "";
            //        foreach (var aacl in jldt.Columns)
            //        {
            //            clnames += aacl + "------";
            //        }
            //        carddata.Add(clnames);
            //        foreach (DataRow  jldtdr in jldt.Rows )
            //        {
            //             clnames = "";
            //            for (int iii = 0; iii < jldt.Columns.Count; iii++)
            //            {

            //                //carddata.Add(aadr[0] + "---" + aadr[1] + "---" + aadr[2] + "---" + aadr[3]);

            //                clnames += jldtdr[iii]+"-----";


            //                //carddata.Add(String .Join ("---",aadr.ItemArray));
            //            }
            //            carddata.Add(clnames);

            //        }
                   
            //        continue;
            //    }

            //    执行结果 = cmd(goid, 执行, ref 返回);

            //    carddata.Add("");
            //    carddata.Add(文本显示);

            //    if (返回 == "9000")
            //    {
            //        DataRow[] drs = ds.Tables["解析"].Select("命令_Id=" + 命令_id);
            //        foreach (DataRow ddrr in drs)
            //        {
            //            string 文本 = ddrr["文本"].ToString().Trim();
            //            string 开始位 = ddrr["开始位"].ToString().Trim();
            //            string 长度 = ddrr["长度"].ToString().Trim();
            //            string 转换方法 = ddrr["转换方法"].ToString().Trim();
            //            string 截取值="";

            //            if (开始位 == "")
            //            {
            //                截取值 = 执行结果.Substring(0, 执行结果.Length - 4);
            //            }
            //            else
            //            {
            //                截取值 = 执行结果.Substring(int.Parse(开始位) * 2 - 2, int.Parse(长度) * 2);
            //            }

            //            switch (转换方法.ToUpper())
            //            {
            //                case "ASC":
            //                    截取值 = ASCtoGB(截取值);
            //                    break;
            //                case "16TO10":
            //                    截取值 = (Convert.ToInt32(截取值, 16)).ToString();
            //                    break;
            //                case "身份证件":
            //                    截取值 = 身份证件(截取值).ToString();
            //                    break;
            //            }

            //            string 输出值 = "";
            //            if (ds.Tables["解析"].Columns.Contains("解析_Id") == true)
            //            {
            //                string 解析_Id = ddrr["解析_Id"].ToString().Trim();

            //                DataRow[] 判断dr = ds.Tables["判断"].Select("解析_Id=" + 解析_Id + " and 条件='" + 截取值 + "'");

            //                if (判断dr.Length > 0)
            //                {
            //                    输出值 = 判断dr[0]["判断_Text"].ToString().Trim();
            //                }
            //                else
            //                {
            //                    输出值 =  截取值;
            //                }
            //            }
            //            else
            //            {
            //                输出值 = 截取值;
            //            }

            //            carddata.Add(String.Format(文本, 输出值));

            //        }
            //    }

                


            //}

            

            //00B0850000
            //string strm1 = "00B0850000"; //000046463937453946463945344620202020202020203631303130333139383630393239323431362020202020202020202020202020009000
            //byte lenm1 = (byte)(strm1.Length / 2);
            //byte rlenm1 = 0;
            //byte[] sbuffm1 = System.Text.Encoding.ASCII.GetBytes(strm1);
            //byte[] rbuffm1 = new byte[300];

            //i = dc_pro_commandlink_hex(goid, lenm1, ref sbuffm1[0], ref rlenm1, ref rbuffm1[0], 7, 56);
            //string Meesm1 = System.Text.Encoding.ASCII.GetString(rbuffm1).Replace("\0", "");
            //string Meessm1 = HP_bytetostrremove(rbuffm1, 4);
            //if (i != 0 || Meessm1 != "9000")
            //{
            //    //MessageBox.Show("16文件读取不成功！");
            //    dc_exit(goid);
            //    return;
            //}

            // carddata= Meesm1.Substring(4, 40);

            // carddata = ASCtoGB(carddata);

            ////////////////////////////////////////////////
            ////string strm = "805C000204";
            ////byte lenm = (byte)(strm.Length / 2);
            ////byte rlenm = 0;
            ////byte[] sbuffm = System.Text.Encoding.ASCII.GetBytes(strm);
            ////byte[] rbuffm = new byte[300];

            ////i = dc_pro_commandlink_hex(goid, lenm, ref sbuffm[0], ref rlenm, ref rbuffm[0], 7, 56);
            ////string Meesm = System.Text.Encoding.ASCII.GetString(rbuffm).Replace("\0", "");
            ////string Meessm = HP_bytetostrremove(rbuffm, 4);
            ////ymoney = Meesm.Remove(8);
            ////if (i != 0 || Meessm != "9000")
            ////{
            ////    MessageBox.Show("读取余额不成功！");
            ////}
            //////////////////////////////////////////////////
            ////i = hp_comm(goid, "00A4040009A00000000386980701");////选择应用

            ////if (i != 0)
            ////{
            ////    return;
            ////}

            ////00B0950000
            ////00A40000020016

            //string strm1 = "00B0960000"; //000046463937453946463945344620202020202020203631303130333139383630393239323431362020202020202020202020202020009000
            //byte lenm1 = (byte)(strm1.Length / 2);
            //byte rlenm1 = 0;
            //byte[] sbuffm1 = System.Text.Encoding.ASCII.GetBytes(strm1);
            //byte[] rbuffm1 = new byte[300];

            //i = dc_pro_commandlink_hex(goid, lenm1, ref sbuffm1[0], ref rlenm1, ref rbuffm1[0], 7, 56);
            //string Meesm1 = System.Text.Encoding.ASCII.GetString(rbuffm1).Replace("\0", "");
            //string Meessm1 = HP_bytetostrremove(rbuffm1, 4);
            //if (i != 0 || Meessm1 != "9000")
            //{
            //    //MessageBox.Show("16文件读取不成功！");
            //    dc_exit(goid);
            //    return;
            //}

            // carddata= Meesm1.Substring(4, 40);

            // carddata = ASCtoGB(carddata);
            ////DataRow[] rows = aaa(goid).Select("1=1");
            ////string[] arr = rows.s.Select(x => x[0].ToString()).ToArray();
           
            dc_exit(goid);
            ////MessageBox.Show("操作成功！");

        }

        public static DataTable  记录文件(int goid,DataSet ds,DataRow dr)
        {
            //StringBuilder strbb = new StringBuilder();
            int 起始条数 = int.Parse (dr["起始条数"].ToString().Trim());
            string 执行 = dr["执行"].ToString().Trim();
            int 条数 = int.Parse (dr["条数"].ToString().Trim());
            string 排序 = dr["排序"].ToString().Trim();
            string 命令_id = dr["命令_id"].ToString().Trim();
            DataRow[] drs = ds.Tables["解析"].Select("命令_Id=" + 命令_id);

            DataTable dt = new DataTable();
            if (dt.Columns.Count == 0)
            {
                //dt.Columns.Add("序号");
                //dt.Columns.Add("交易类型");
                //dt.Columns.Add("交易金额");
                //dt.Columns.Add("交易日期");
                //foreach (DataRow adr in drs)
                //{

                //    dt.Columns.Add(adr["文本"].ToString());
                //}
                //dt.Columns.Add("str");

                foreach (DataRow adr in drs)
                {

                    dt.Columns.Add(adr["文本"].ToString());
                }

            }
            string 返回 = "";
            string 执行结果 = "";
            int iid = 10;
            for (int i = 起始条数; i <= 条数; i++)
            {

                string striii = Convert.ToString(i, 16).PadLeft(2, '0');
                //读取应用
                //err = CK.A6.comd.send("00B2" + striii + "C417", serialPort1, out outstr);
                //C4 = 短文件标识 + 100;
                //执行结果 = cmd(goid, "00B2" + striii + "C417", ref 返回);

                string ccmm = string.Format(执行, striii);
                执行结果 = cmd(goid, ccmm, ref 返回);

                if (执行结果 == null)
                {
                    break;
                }
                //if (执行结果.Length != 50)
                //{
                //    break;
                //}
                //StringBuilder strbbb = new StringBuilder();
                var ddrr = dt.NewRow();
                foreach (DataRow adr in drs)
                {
                    /////
                    string 文本1 = adr["文本"].ToString().Trim();
                    string 开始位1 = adr["开始位"].ToString().Trim();
                    string 长度1 = adr["长度"].ToString().Trim();
                    string 转换方法1 = adr["转换方法"].ToString().Trim();
                    string 截取值1 = "";
                    if (开始位1 == "")
                    {
                        截取值1 = 执行结果.Substring(0, 执行结果.Length - 4);
                    }
                    else
                    {
                        截取值1 = 执行结果.Substring(int.Parse(开始位1) * 2 - 2, int.Parse(长度1) * 2);
                    }

                    switch (转换方法1.ToUpper())
                    {
                        case "ASC":
                            截取值1 = ASCtoGB(截取值1);
                            break;
                        case "16TO10":
                            截取值1 = (Convert.ToInt32(截取值1, 16)).ToString();
                            break;
                        case "日期":
                            if (截取值1 == "00000000000000" || 截取值1 == "FFFFFFFFFFFFFF")
                            {
                                break;
                            }
                            DateTime dt1 = DateTime.ParseExact(截取值1, "yyyyMMddHHmmss", null);
                            截取值1 = dt1.ToString("yyyy-MM-dd HH:mm:ss");
                            break ;
                    }

                    ///////
                    string 输出值 = "";
                    if (ds.Tables["解析"].Columns.Contains("解析_Id") == true)
                    {
                        string 解析_Id = adr["解析_Id"].ToString().Trim();

                        DataRow[] 判断dr = ds.Tables["判断"].Select("解析_Id=" + 解析_Id + " and 条件='" + 截取值1 + "'");

                        if (判断dr.Length > 0)
                        {
                            输出值 = 判断dr[0]["判断_Text"].ToString().Trim();
                        }
                        else
                        {
                            输出值 = 截取值1;
                        }
                    }
                    else
                    {
                        输出值 = 截取值1;
                    }

                    //strbbb.Append(输出值+"---");

                    //dt.Rows .Add  (String.Format(文本1, 输出值));

                    ddrr[文本1] = 输出值;
                    //////
                    
                }

                dt.Rows.Add(ddrr);
                iid--;
            }

            if (排序.Trim().Length > 0)
            {
                dt.DefaultView.Sort = 排序;
            }
            DataTable dtTemp = dt.DefaultView.ToTable();

            return dtTemp;
        }


        public static DataTable  aaa(int goid)
        {
            DataTable dt=new DataTable ();
            if (dt.Columns.Count == 0)
            {
                dt.Columns.Add("序号");
                dt.Columns.Add("交易类型");
                dt.Columns.Add("交易金额");
                dt.Columns.Add("交易日期");
                //dt.Columns.Add("交易时间");
            }
            string 返回 = "";
            string 执行结果 = "";
            int iid = 10;
            for (int i = 1; i <= 10; i++)
            {

                string striii = Convert.ToString (i, 16).PadLeft(2, '0');
                //读取应用
                //err = CK.A6.comd.send("00B2" + striii + "C417", serialPort1, out outstr);
                //C4 = 短文件标识 + 100;
                执行结果=cmd(goid, "00B2" + striii + "C417", ref 返回);

                if (执行结果 == null)
                {
                    break;
                }
                if (执行结果.Length != 50)
                {
                    break;
                }
                //arr.Add (outstr);
                //0BBB000000000000640671000100471920141113101746
                string 交易日期 = 执行结果.Substring(32, 14);
                if (交易日期 == "00000000000000" ||交易日期== "FFFFFFFFFFFFFF")
                {
                    break;
                }
                //交易日期 = DateTime.ParseExact(交易日期, "yyyyMMddhhmmss", new System.Globalization.CultureInfo("zh-CN", true)).ToString();

                DateTime dt1 = DateTime.ParseExact(交易日期, "yyyyMMddHHmmss", null);
                //string 交易时间 = outstr.Substring(40, 6);
                交易日期 = dt1.ToString("yyyy-MM-dd HH:mm:ss");
                string 交易类型 = "";
                string lx = 执行结果.Substring(18, 2);
                switch (lx)
                {
                        //02：充资
                        //06：消费
                        //09：复合消费
                    case "02":
                        交易类型 = "充资";
                        break;
                    case "06":
                        交易类型 = "消费";
                        break;
                    case "09":
                        交易类型 = "复合消费";
                        break;
                }
                string 交易金额 = (Convert.ToInt32(执行结果.Substring(10, 8), 16) * 0.01).ToString() + "元";
                dt.Rows.Add(iid, 交易类型, 交易金额, 交易日期);
                //if (err == false)
                //{
                //    return err;
                //}
                iid--;
            }

            dt.DefaultView.Sort = "交易日期 deSC";
            DataTable dtTemp = dt.DefaultView.ToTable();

            return dtTemp;
        }


        public static string cmd(int goid,string strm1,ref string fh)
        {
            fh = "0";
            //string strm1 = "00B0850000"; //000046463937453946463945344620202020202020203631303130333139383630393239323431362020202020202020202020202020009000
            byte lenm1 = (byte)(strm1.Length / 2);
            byte rlenm1 = 0;
            byte[] sbuffm1 = System.Text.Encoding.ASCII.GetBytes(strm1);
            byte[] rbuffm1 = new byte[300];

            int i = dc_pro_commandlink_hex(goid, lenm1, ref sbuffm1[0], ref rlenm1, ref rbuffm1[0], 7, 56);
            string Meesm1 = System.Text.Encoding.ASCII.GetString(rbuffm1).Replace("\0", "");
            string Meessm1 = HP_bytetostrremove(rbuffm1, 4);
            fh = Meessm1;
            if (i != 0 || Meessm1 != "9000")
            {
                //MessageBox.Show("16文件读取不成功！");
                dc_exit(goid);
                return "ERR:"+Meessm1;
            }
            return Meesm1;
            //carddata = Meesm1.Substring(4, 40);
            //carddata = ASCtoGB(carddata);
        }

        //public static string sub()
        //{
        //    string ms = "869871000000FF18710001030589979601032014022100000000000300019000";

        //    return "";
        //}


        public static string HexTo10(string str)
        {
            return  Convert.ToInt32(str, 16).ToString ();
        }


        private static bool checkqo(int i)
        {
            if (i % 2 == 0)
            {
                return true;
            }
            else
                return false;
        }

        public static string 身份证件(string str)
        {
            str = str.Substring(0, 36);
            int i = 1;
            string aaa = "";
            foreach (var a in str)
            {
                if(checkqo(i)==false)
                {
                    if (a == '3')
                    {
                        i++;
                        continue;
                    }
                }
                i++;
                
                aaa += a;
            }

            if (aaa.Length == 18)
                return aaa;
            else
            {
                return aaa.Substring(0, 17) + "X";
            }


        }
        /// <summary>
        /// 获取卡内号
        /// </summary>
        public static ulong GetCradNum()
        {
            int goid = HP.currency.dc_init(100, 115200);//取设备标识;
            if (goid <= 0) //返加>0成功
            {
              
                //MessageBox.Show("设备没有打开！");
                return 0;
            }

            /////////////////////////////////////////
            //操作消费卡开始
            int i = 999;//成功标识
            //////////////////////////////////////////

            i = HP.currency.dc_config_card(goid, 'A');
            if (i != 0)
            {
                //MessageBox.Show("设置卡类型不成功！");
                dc_exit(goid);
                return 1;
            }

            ///////////////////////////////////////

            i = HP.currency.dc_reset(goid, 1);
            if (i != 0)
            {
                //MessageBox.Show("射频复位不成功！");
                dc_exit(goid);
                return 2;
            }

            //////////////////////////////////////

            ulong icCardNo = 0;//返回的卡序列号
            for (int ii = 0; ii <= 10; ii++)
            {
                //i = HP.currency.dc_card(goid, '0', ref icCardNo);
                //if (i != 0)
                //{
                //    //MessageBox.Show("寻卡不成功！");
                //    dc_exit(goid);
                //    return 3;

                //}
                if (icCardNo > 0)
                {
                    break;
                }
                try
                {
                    i = HP.currency.dc_card(goid, '0', ref icCardNo);
                }
                catch
                {
                    dc_exit(goid);
                    break;
                }
               
                //if (i != 0)
                //{
                //    //MessageBox.Show("寻卡不成功！");
                //    dc_exit(goid);
                //    return 3;

                //}
            }

            if (icCardNo == 0)
            {
                //MessageBox.Show("寻卡不成功！");
                dc_exit(goid);
                return 3;

            }

            dc_exit(goid);
            return icCardNo;

        }

        /// <summary>
        /// 卡ASC转汉字已
        /// </summary>
        /// <param name="card"></param>
        /// <returns></returns>
        //public static string ASCtoGB(string card)
        //{
        //    string ddd = HexToASCII("4646393745394646394534462020202020202020").Replace(" ", "");
        //   // string ddd = HexToASCII(card).Replace(" ", "");
        //    string[] dssd = SplitByLen(ddd, 6);

        //    string Unicodestr = "";
        //    foreach (string i in dssd)
        //    {
        //        Unicodestr += TrimStarString(i, "FF", @"\u");
        //    }

        //    string ddds = Unicode2String(Unicodestr);

        //    return ddds;
        //}
        public static string ASCtoGB(string card)
        {

            string ddd = HexToASCII(card).Replace(" ", "");
            string Unicodestr = "";//"\\u" + a + "\\u" + b
            string[] dssd = SplitByLen(ddd, 4);

            foreach (string i in dssd)
            {
                Unicodestr += "\\u" + i;
            }
            string ddds = Unicode2String(Unicodestr);
            return ddds;
        }



        public static string HexToStr(string Msg)
        {
            byte[] buff = new byte[Msg.Length / 2];
            string Message = "";
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = byte.Parse(Msg.Substring(i * 2, 2),
                   System.Globalization.NumberStyles.HexNumber);
            }

            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");
            Message = chs.GetString(buff);
            return Message;
        }


        public static string wxHexToASCII(string Msg)
        {
            byte[] buff = new byte[Msg.Length / 2];
            string Message = "";
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = byte.Parse(Msg.Substring(i * 2, 2),
                   System.Globalization.NumberStyles.HexNumber);
            }

            System.Text.Encoding chs = System.Text.Encoding.ASCII;
            Message = chs.GetString(buff);
            return Message;
        }








        public static string HexToASCII(string Msg)
        {
            byte[] buff = new byte[Msg.Length / 2];
            string Message = "";
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = byte.Parse(Msg.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }

            System.Text.Encoding chs = System.Text.Encoding.ASCII;

           
            Message = chs.GetString(buff);
            return Message;
        }

        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="source">经过Unicode编码的字符串</param>
        /// <returns>正常字符串</returns>
        public static string Unicode2String(string source)
        {
            return new System.Text.RegularExpressions.Regex(@"\\u([0-9A-F]{4})", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled).Replace(
                         source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
        }

        /// <summary>  
        /// 按字符串长度切分成数组  
        /// </summary>  
        /// <param name="str">原字符串</param>  
        /// <param name="separatorCharNum">切分长度</param>  
        /// <returns>字符串数组</returns>  
        public static string[] SplitByLen(string str, int separatorCharNum)
        {
            if (string.IsNullOrEmpty(str) || str.Length <= separatorCharNum)
            {
                return new string[] { str };
            }
            string tempStr = str;
            List<string> strList = new List<string>();
            int iMax = Convert.ToInt32(Math.Ceiling(str.Length / (separatorCharNum * 1.0)));//获取循环次数  
            for (int i = 1; i <= iMax; i++)
            {
                string currMsg = tempStr.Substring(0, tempStr.Length > separatorCharNum ? separatorCharNum : tempStr.Length);
                strList.Add(currMsg);
                if (tempStr.Length > separatorCharNum)
                {
                    tempStr = tempStr.Substring(separatorCharNum, tempStr.Length - separatorCharNum);
                }
            }
            return strList.ToArray();
        }

        /// <summary>
        /// 替换字符串起始位置(开头)中指定的字符串
        /// </summary>
        /// <param name="s">源串</param>
        /// <param name="searchStr">查找的串</param>
        /// <param name="replaceStr">替换的目标串</param>
        /// <returns></returns>
        public static string TrimStarString(string s, string searchStr, string replaceStr)
        {
            var result = s;
            try
            {
                if (string.IsNullOrEmpty(result))
                {
                    return result;
                }
                if (s.Length < searchStr.Length)
                {
                    return result;
                }
                if (s.IndexOf(searchStr, 0, searchStr.Length, StringComparison.Ordinal) > -1)
                {
                    result = replaceStr + s.Substring(searchStr.Length);
                }
                return result;
            }
            catch (Exception e)
            {
                return result;
            }
        }

    }

}

